package main

import (
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
	"gorm.io/gorm/logger"
	"shortUrl/common/helper"
	"shortUrl/internal/config"
	"shortUrl/internal/handler"
	"shortUrl/internal/svc"
)

var configFile = flag.String("f", "etc/config.yaml", "the config file")
var c config.Config
var db config.DataBaseConf
var cacheDb config.CacheConf
var business config.BusinessConf

func main() {
	flag.Parse()
	conf.MustLoad(*configFile, &c)
	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()
	//从配置中心获取业务配置
	loadConfFromConfigCenter()

	//初始化服务资源池
	ctx := svc.NewServiceContext(c, &db, &cacheDb, &business)
	handler.RegisterHandlers(server, ctx)
	fmt.Printf("Starting server at %s:%d...\n", c.RestConf.Host, c.RestConf.Port)
	server.Start()
}

func loadConfFromConfigCenter() {
	//获取配置中心客户端
	cc := config.NewClient(&c)
	if helper.IsProduction(c.App.Env) {
		db.LogLevel = logger.Silent
	} else {
		db.LogLevel = logger.Info
	}
	//启动config监听
	config.WatchConfig(cc, "database", c.Name, &db)
	config.WatchConfig(cc, "redis", c.Name, &cacheDb)
	config.WatchConfig(cc, "business", c.Name, &business)
}
